using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Authorization.Users;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Abp.Organizations;
using System.Linq.Dynamic.Core;
using Abp.AutoMapper;
using Abp.Domain.Entities;
using Abp.UI;
using Microsoft.EntityFrameworkCore;
using JYJ.AiYard.Authorization;
using JYJ.AiYard.Organizations.Dtos;
using JYJ.AiYard.Authorization.Roles;
using JYJ.AiYard.StationManagement.TbStations;
using JYJ.AiYard.StationManagement.TbStations.DomainService;
using JYJ.AiYard.StationManagement.TbStations.Dtos;
using Remotion.Linq.Clauses;
using Senparc.Weixin.MP.AdvancedAPIs.GroupMessage;
using JYJ.AiYard.Database;
using System.Text;

namespace JYJ.AiYard.Organizations
{
    public class MyOrganizationUnit : OrganizationUnit
    {
        public int MemberCount { get; set; }
        public int RoleCount { get; set; }
    }

    /// <summary>
    /// 组织单元服务
    /// </summary>
    [AbpAuthorize(YoyoSoftPermissionNames.Pages_Administration_OrganizationUnits)]
    public class OrganizationUnitAppService : AiYardAppServiceBase, IOrganizationUnitAppService
    {
        #region OrganizationUnit private

        private async Task<OrganizationUnitListDto> CreateOrganizationUnit(OrganizationUnit organizationUnit)
        {
            var dto = ObjectMapper.Map<OrganizationUnitListDto>(organizationUnit);
            dto.MemberCount =
                await _userOrganizationUnitRepository.CountAsync(uou => uou.OrganizationUnitId == organizationUnit.Id);
            return dto;
        }

        #endregion

        #region 初始化

        private readonly OrganizationUnitManager _organizationUnitManager;
        private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository;
        private readonly IRepository<UserOrganizationUnit, long> _userOrganizationUnitRepository;
        private readonly IRepository<OrganizationUnitRole, long> _organizationUnitRoleRepository;
        private readonly RoleManager _roleManager;
        private readonly TbStationManager _tbstationManager;
        private readonly IRepository<TbStation, long> _tbstationRepository;
        private readonly IAiYardDbTableIssuedCard _aiYardDbTableIssuedCard;

        public OrganizationUnitAppService(
            OrganizationUnitManager organizationUnitManager,
            IRepository<OrganizationUnit, long> organizationUnitRepository,
            IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository,
            RoleManager roleManager,
            IRepository<OrganizationUnitRole, long> organizationUnitRoleRepository,
            TbStationManager tbstationManager,
            IAiYardDbTableIssuedCard aiYardDbTableIssuedCard,
            IRepository<TbStation, long> tbstationRepository
            )
        {
            _organizationUnitManager = organizationUnitManager;
            _organizationUnitRepository = organizationUnitRepository;
            _userOrganizationUnitRepository = userOrganizationUnitRepository;
            _roleManager = roleManager;
            _organizationUnitRoleRepository = organizationUnitRoleRepository;
            _tbstationManager = tbstationManager;
            _tbstationRepository = tbstationRepository;
            _aiYardDbTableIssuedCard = aiYardDbTableIssuedCard;
        }

        #endregion


        #region OrganizationUnit public

        #region 获取场所树
        /// <summary>
        /// 通过组织ID获取TbStationListDto信息
        /// </summary>
        public async Task<TbStationListDto> GetTbStationByStationId(EntityDto<long> input)
        {
            var entity = await _tbstationRepository.SingleAsync(o => input.Id == o.Station_Id);
            return entity.MapTo<TbStationListDto>();
        }

        public async Task<ListResultDto<OrganizationUnitListDto>> GetAllOrganizationUnitList()
        {
            //首先获取当前用户组织 
            var getOrganId = from ou in _userOrganizationUnitRepository.GetAll().Where(t => t.UserId == AbpSession.UserId && !t.IsDeleted) select ou;
            
            if (getOrganId.ToList<UserOrganizationUnit>().Count <= 0)
            { 
                //当前用户没有组织，返回整棵组织树
                var query =
                    from ou in _organizationUnitRepository.GetAll()
                    join uou in _userOrganizationUnitRepository.GetAll() on ou.Id equals uou.OrganizationUnitId 
                    into g
                    where !ou.IsDeleted
                    select new OrganizationUnitListDto
                    { Id = ou.Id, ParentId = ou.ParentId, Code = ou.Code, DisplayName = ou.DisplayName, RoleCount = 0, 
                                 MemberCount = g.Count() };


                var items = await query.ToListAsync();
                 
                ListResultDto<OrganizationUnitListDto> li = new ListResultDto<OrganizationUnitListDto>(
                   items.Select(item =>
                   {  
                       var dto = ObjectMapper.Map<OrganizationUnitListDto>(item);
                       dto.MemberCount = item.MemberCount;
                       return dto;
                   }).ToList());
                return li;
            }
            else
            {


                var query1 = GetOrganizationUnit2(getOrganId.ToList<UserOrganizationUnit>()[0].OrganizationUnitId, 1);
            
                var items1 = query1.ToList();
                ListResultDto<OrganizationUnitListDto> li1 =
                    new ListResultDto<OrganizationUnitListDto>(
                        items1.Select(item1 =>
                        {
                            var dto1 = ObjectMapper.Map<OrganizationUnitListDto>(item1);
                            //dto1.MemberCount = item1.MemberCount;
                            return dto1;
                        }).ToList()
                    );
                li1.Items[0].ParentId = null;
                return li1;
            }
             
        }

        public IEnumerable<OrganizationUnitListDto> GetOrganizationUnit2(long k,    int first)
        {

             
            if (first == 1)
            {
               var query = from ou in _organizationUnitRepository.GetAll()
                    join uou in _userOrganizationUnitRepository.GetAll() on ou.Id equals uou.OrganizationUnitId into g
                    where  ou.Id == k && !ou.IsDeleted
                    select new OrganizationUnitListDto
                    {
                        Id = ou.Id, ParentId = ou.ParentId, Code = ou.Code, DisplayName = ou.DisplayName, RoleCount = 0,
                        MemberCount = g.Count()
                    }; 
               return query.ToList().Concat(query.ToList().SelectMany(t => GetOrganizationUnit2(t.Id, 2)));
            }
            else
            {

              var  query = from ou in _organizationUnitRepository.GetAll()
                    join uou in _userOrganizationUnitRepository.GetAll() on ou.Id equals uou.OrganizationUnitId into g
                    where ou.ParentId == k && !ou.IsDeleted
                    select new OrganizationUnitListDto
                    {
                        Id = ou.Id,
                        ParentId = ou.ParentId,
                        Code = ou.Code,
                        DisplayName = ou.DisplayName,
                        RoleCount = 0,
                        MemberCount = g.Count()
                    }; 
              return query.ToList().Concat(query.ToList().SelectMany(t => GetOrganizationUnit2(t.Id, 2)));
            }

            
        }
        #endregion

        #region 场所添加
        [AbpAuthorize(YoyoSoftPermissionNames.Pages_Administration_OrganizationUnits_ManageOrganizationTree_AddRootNode,
            YoyoSoftPermissionNames.Pages_Administration_OrganizationUnits_ManageOrganizationTree_AddSubNode)]
        public async Task<OrganizationUnitListDto> Create(CreateOrganizationUnitInput input)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();

            bool IsAssess = true;  //检验是否通过

            #region 检验是否OK
            //判断场所编号不能重复--所有租户
            var tbquery = await _tbstationRepository.GetAll().Where(o => o.Station_No == input.Station_No).ToListAsync();
            if (tbquery.Count > 0)
            {
                IsAssess = false;
                //已经存在重复
                result.Add("retype", "-1");
                result.Add("revalue", "场所编号重复");
            }

            if (IsAssess)
            {
                if (string.IsNullOrEmpty(input.Station_Name.Trim()))
                {
                    IsAssess = false;
                    result.Add("retype", "-1");
                    result.Add("revalue", "场所名称为空");
                }
            }

            if (IsAssess)
            {
                if (string.IsNullOrEmpty(input.Station_Tel.Trim()))
                {
                    IsAssess = false;
                    result.Add("retype", "-1");
                    result.Add("revalue", "电话号码为空");
                }
            }

            if (IsAssess)
            {
                if (string.IsNullOrEmpty(input.Station_MD5Key.Trim()))
                {
                    IsAssess = false;
                    result.Add("retype", "-1");
                    result.Add("revalue", "MD5Key为空");
                }
                else
                {
                    if (input.Station_MD5Key.Trim().Length != 32)
                    {
                        IsAssess = false;
                        result.Add("retype", "-1");
                        result.Add("revalue", "MD5Key必须为32位字符串");
                    }
                }
            }
            #endregion

            if (IsAssess)
            {
                input.DisplayName = input.Station_Name;
                var organizationUnit = new OrganizationUnit(AbpSession.TenantId, input.DisplayName, input.ParentId);
                await _organizationUnitManager.CreateAsync(organizationUnit);
                // var id = _organizationUnitRepository.InsertAndGetIdAsync(organizationUnit);
                await CurrentUnitOfWork.SaveChangesAsync();

                //添加其它信息

                if (organizationUnit == null)
                {
                    result.Add("retype", "-1");
                    result.Add("revalue", "添加不成功");
                    throw new UserFriendlyException("添加不成功");
                }
                else
                {
                    if (!organizationUnit.Id.Equals(null))
                    {
                        TbStation tb = new TbStation();
                        tb.Station_Id = organizationUnit.Id;
                        tb.Customer_Id = input.Customer_Id;
                        tb.Station_Address = input.Station_Address;
                        tb.Station_FullName = input.Station_FullName;
                        tb.Station_MD5Key = input.Station_MD5Key;
                        tb.Station_Mail = input.Station_Mail;
                        tb.Station_Name = input.Station_Name;
                        tb.Station_No = input.Station_No;
                        tb.Station_Stop = input.Station_Stop;
                        tb.Station_Tel = input.Station_Tel;
                        tb.Station_Type = input.Station_Type;
                        tb.Station_Validity = input.Station_Validity;
                        tb.Station_UpLoad = input.Station_UpLoad;
                        tb.Station_lati = input.Station_lati;
                        tb.Station_latiPlus = input.Station_latiPlus;
                        tb.Station_latiReduce = input.Station_latiReduce;
                        tb.Station_long = input.Station_long;
                        tb.Station_longPlus = input.Station_longPlus;
                        tb.Station_longReduce = input.Station_longReduce;
                        await _tbstationRepository.InsertAsync(tb);
                        result.Add("retype", "1");
                        result.Add("revalue", "添加成功");
                    }

                    //organizationUnit.Id
                }
                OrganizationUnitListDto resultDto = ObjectMapper.Map<OrganizationUnitListDto>(organizationUnit);
                resultDto.resultDto = result;
                return resultDto;
            }
            else
            {
                OrganizationUnitListDto resultDto = new OrganizationUnitListDto();
                resultDto.resultDto = result;
                return resultDto;
            }

           
            //return result;
        }
        #endregion

        #region 删除场所
        [AbpAuthorize(YoyoSoftPermissionNames.Pages_Administration_OrganizationUnits_ManageOrganizationTree_DeleteNode)]
        public async Task Delete(EntityDto<long> input)
        {
            await _organizationUnitManager.DeleteAsync(input.Id);
            //删除TbStation数据
            await _tbstationManager.DeleteByStationId(input.Id);
        }
        #endregion

        #region 编辑场所
        [AbpAuthorize(YoyoSoftPermissionNames.Pages_Administration_OrganizationUnits_ManageOrganizationTree_EditNode)]
        public async Task<OrganizationUnitListDto> Update(UpdateOrganizationUnitInput input)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();

            bool IsAssess = true;  //检验是否通过
            #region 检验是否OK
            //判断场所编号不能重复--所有租户
            var tbquery = await _tbstationRepository.GetAll().Where(o => o.Station_Id != input.Station_Id && o.Station_No == input.Station_No).ToListAsync();
            if (tbquery.Count > 0)
            {
                IsAssess = false;
                //已经存在重复
                result.Add("retype", "-1");
                result.Add("revalue", "场所编号重复");
            }

            if (IsAssess)
            {
                if (string.IsNullOrEmpty(input.Station_Name.Trim()))
                {
                    IsAssess = false;
                    result.Add("retype", "-1");
                    result.Add("revalue", "场所名称为空");
                }
            }

            if (IsAssess)
            {
                if (string.IsNullOrEmpty(input.Station_Tel.Trim()))
                {
                    IsAssess = false;
                    result.Add("retype", "-1");
                    result.Add("revalue", "电话号码为空");
                }
            }

            if (IsAssess)
            {
                if (string.IsNullOrEmpty(input.Station_MD5Key.Trim()))
                {
                    IsAssess = false;
                    result.Add("retype", "-1");
                    result.Add("revalue", "MD5Key为空");
                }
                else
                {
                    if (input.Station_MD5Key.Trim().Length != 32)
                    {
                        IsAssess = false;
                        result.Add("retype", "-1");
                        result.Add("revalue", "MD5Key必须为32位字符串");
                    }
                }
            }
            #endregion

            if (IsAssess)
            {
                var organizationUnit = await _organizationUnitRepository.GetAsync(input.Id);

                if (organizationUnit == null)
                {
                    result.Add("retype", "-1");
                    result.Add("revalue", "指定组织不存在");
                }
                //   throw new UserFriendlyException("指定组织不存在");
                else
                {
                    if (!organizationUnit.Id.Equals(null))
                    {
                        var tb = await _tbstationRepository.SingleAsync(o => organizationUnit.Id == o.Station_Id);

                        //TbStation tb = new TbStation();
                        //tb.StationId = organizationUnit.Id;
                        tb.Customer_Id = input.Customer_Id;
                        tb.Station_Address = input.Station_Address;
                        tb.Station_FullName = input.Station_FullName;
                        tb.Station_MD5Key = input.Station_MD5Key;
                        tb.Station_Mail = input.Station_Mail;
                        tb.Station_Name = input.Station_Name;
                        tb.Station_No = input.Station_No;
                        tb.Station_Stop = input.Station_Stop;
                        tb.Station_Tel = input.Station_Tel;
                        tb.Station_Type = input.Station_Type;
                        tb.Station_Validity = input.Station_Validity;
                        tb.Station_UpLoad = input.Station_UpLoad;
                        tb.Station_lati = input.Station_lati;
                        tb.Station_latiPlus = input.Station_latiPlus;
                        tb.Station_latiReduce = input.Station_latiReduce;
                        tb.Station_long = input.Station_long;
                        tb.Station_longPlus = input.Station_longPlus;
                        tb.Station_longReduce = input.Station_longReduce;
                        await _tbstationRepository.UpdateAsync(tb);

                    }
                    else
                    {
                        result.Add("retype", "-1");
                        result.Add("revalue", "ID不为空");
                    }

                    //organizationUnit.Id
                }

                organizationUnit.DisplayName = input.Station_Name;

                await _organizationUnitManager.UpdateAsync(organizationUnit);

                await CreateOrganizationUnit(organizationUnit);
                OrganizationUnitListDto resultDto = ObjectMapper.Map<OrganizationUnitListDto>(organizationUnit);
                if (result.Count <= 0)
                {
                    result.Add("retype", "1");
                    result.Add("revalue", "保存成功");
                }
                resultDto.resultDto = result;
                return resultDto;
            }
            else
            {
                OrganizationUnitListDto resultDto = new OrganizationUnitListDto();
                if (result.Count <= 0)
                {
                    result.Add("retype", "1");
                    result.Add("revalue", "保存成功");
                }
                resultDto.resultDto = result;
                return resultDto;
            }
        }
        #endregion

        #region 移动场所
        [AbpAuthorize(YoyoSoftPermissionNames.Pages_Administration_OrganizationUnits_ManageOrganizationTree_MoveNode)]
        public async Task<OrganizationUnitListDto> Move(MoveOrganizationUnitInput input)
        {
            await _organizationUnitManager.MoveAsync(input.Id, input.NewParentId);

            return await CreateOrganizationUnit(
                await _organizationUnitRepository.GetAsync(input.Id)
            );
        }
        #endregion

        #region 生成一个临时的秘钥
        /// <summary>
        /// 生成一个临时的秘钥
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize(YoyoSoftPermissionNames.Pages_Administration_OrganizationUnits_ManageOrganizationTree_CreatePW)]
        public async Task<string> CreatePassWord()
        {
            string str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            
            StringBuilder SB = new StringBuilder();
            Random rd = new Random();
            for (int i = 0; i < 6; i++)
            {
                SB.Append(str.Substring(rd.Next(0, str.Length), 1));
            }
            _aiYardDbTableIssuedCard.InitYardParams(-1, -1, "TempPasswordToRegDevs", "127.0.0.1", "临时密码用来加密设备", "STRING", SB.ToString(), true);
            return _aiYardDbTableIssuedCard.GetTbStationParamTablePassword();
        }
        #endregion

        #region 开启B账功能
        [AbpAuthorize(YoyoSoftPermissionNames.Pages_Administration_OrganizationUnits_ManageOrganizationTree_HideStation)]
        public async Task<string> OpenBAccount(string StationNo)
        {
            return _aiYardDbTableIssuedCard.OpenBAccount(StationNo).ToString();
        }
        #endregion

        #endregion


        #region Organization User public

        [AbpAuthorize(YoyoSoftPermissionNames.Pages_Administration_OrganizationUnits_ManageUsers)]
        public async Task<PagedResultDto<OrganizationUnitUserListDto>> GetPagedOrganizationUnitUsers(
            GetOrganizationUnitUsersInput input)
        {
            try
            {
                var query = from uou in _userOrganizationUnitRepository.GetAll()
                            join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id
                            join user in UserManager.Users.WhereIf(!input.FilterText.IsNullOrWhiteSpace(), u => u.UserName.Contains(input.FilterText)) on uou.UserId equals user.Id
                            where uou.OrganizationUnitId == input.Id
                            select new { uou, user };

                var totalCount = await query.CountAsync();
                var items = await query.OrderBy(o => input.Sorting).PageBy(input).ToListAsync();

                return new PagedResultDto<OrganizationUnitUserListDto>(
                    totalCount,
                    items.Select(item =>
                    {
                        var dto = ObjectMapper.Map<OrganizationUnitUserListDto>(item.user);
                        dto.AddedTime = item.uou.CreationTime;
                        return dto;
                    }).ToList());
            }
            catch (Exception e)
            {
                throw new UserFriendlyException(e.Message);
            }
        }

        [AbpAuthorize(YoyoSoftPermissionNames.Pages_Administration_OrganizationUnits_ManageUsers)]
        public async Task AddUsers(UsersToOrganizationUnitInput input)
        {
            foreach (var uids in input.UserIds)
                await UserManager.AddToOrganizationUnitAsync(uids, input.OrganizationUnitId);
        }

        [AbpAuthorize(YoyoSoftPermissionNames.Pages_Administration_OrganizationUnits_ManageUsers)]
        public async Task RemoveUser(UserToOrganizationUnitInput input)
        {
            await UserManager.RemoveFromOrganizationUnitAsync(input.UserId, input.OrganizationUnitId);
        }

        public async Task<bool> IsInOrganizationUnit(UserToOrganizationUnitInput input)
        {
            return await UserManager.IsInOrganizationUnitAsync(input.UserId, input.OrganizationUnitId);
        }

        [AbpAuthorize(YoyoSoftPermissionNames.Pages_Administration_OrganizationUnits_ManageUsers)]
        public async Task<PagedResultDto<NameValueDto>> FindUsers(FindUsersInput input)
        {
            var userIdsInOrganizationUnit = _userOrganizationUnitRepository.GetAll()
                .Where(uou => uou.OrganizationUnitId == input.OrganizationUnitId)
                .Select(uou => uou.UserId);

            var query = UserManager.Users
                .Where(user => !userIdsInOrganizationUnit.Contains(user.Id))
                .WhereIf(
                    !input.FilterText.IsNullOrWhiteSpace(),
                    user =>
                        user.UserName.Contains(input.FilterText) ||
                        user.EmailAddress.Contains(input.FilterText)
                );

            var userCount = await query.CountAsync();
            var users = await query
                .OrderBy(u => u.Name)
                .ThenBy(u => u.Surname)
                .PageBy(input)
                .ToListAsync();

            return new PagedResultDto<NameValueDto>(
                userCount,
                users.Select(user =>
                    new NameValueDto(
                        $"{user.UserName} ({user.EmailAddress})",
                        user.Id.ToString()
                    )
                ).ToList()
            );
        }

        /// <summary>
        ///     批量从组织中移除用户
        /// </summary>
        /// <param name="userIds">用户Id列表</param>
        /// <param name="organizationUnitId">组织机构Id</param>
        /// <returns></returns>
        [AbpAuthorize(YoyoSoftPermissionNames.Pages_Administration_OrganizationUnits_ManageUsers)]
        public async Task BatchRemoveUserFromOrganizationUnit(List<long> userIds, long organizationUnitId)
        {
            await _userOrganizationUnitRepository.DeleteAsync(ou =>
                userIds.Contains(ou.UserId) && ou.OrganizationUnitId == organizationUnitId);
        }

        #endregion


        #region Organization Role public
        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<OrganizationUnitRoleListDto>> GetPagedOrganizationUnitRolesAsync(GetOrganizationUnitRolesInput input)
        {
            var query = from ouRole in _organizationUnitRoleRepository.GetAll()
                        join ou in _organizationUnitRepository.GetAll() on ouRole.OrganizationUnitId equals ou.Id
                        join role in _roleManager.Roles.WhereIf(!input.FilterText.IsNullOrWhiteSpace(),r => r.DisplayName.Contains(input.FilterText)) on ouRole.RoleId equals role.Id
                        where ouRole.OrganizationUnitId == input.Id
                        select new
                        {
                            ouRole,
                            role
                        };

            var totalCount = await query.CountAsync();
            var items = await query.OrderBy(input.Sorting).PageBy(input).ToListAsync();

            return new PagedResultDto<OrganizationUnitRoleListDto>(
                totalCount,
                items.Select(item =>
                {
                    var organizationUnitRoleDto = ObjectMapper.Map<OrganizationUnitRoleListDto>(item.role);
                    organizationUnitRoleDto.AddedTime = item.ouRole.CreationTime;
                    return organizationUnitRoleDto;
                }).ToList());
        }
        /// <summary>
        /// 添加角色 组织关联
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(YoyoSoftPermissionNames.Pages_Administration_OrganizationUnits_ManageRoles)]
        public async Task AddRoles(RolesToOrganizationUnitInput input) {
            foreach (var rids in input.RoleIds)
                await _roleManager.AddToOrganizationUnitAsync(rids, input.OrganizationUnitId, null);
                
        }
        /// <summary>
        /// 删除 角色 组织关联
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(YoyoSoftPermissionNames.Pages_Administration_OrganizationUnits_ManageRoles)]
        public async Task RemoveRole(RoleToOrganizationUnitInput input) {
            await _roleManager.RemoveFromOrganizationUnitAsync(input.RoleId, input.OrganizationUnitId);
        }
        /// <summary>
        /// 判断角色是否在当前组织
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<bool> RolesIsInOrganizationUnit(RoleToOrganizationUnitInput input) {
            return await _roleManager.IsInOrganizationUnitAsync(input.RoleId, input.OrganizationUnitId);
        }
        [AbpAuthorize(YoyoSoftPermissionNames.Pages_Administration_OrganizationUnits_ManageRoles)]
        public async Task<PagedResultDto<NameValueDto>> FindRoles(FindUsersInput input)
        {
            var roleIdsInOrganizationUnit = _organizationUnitRoleRepository.GetAll()
                .Where(uou => uou.OrganizationUnitId == input.OrganizationUnitId)
                .Select(uou => uou.RoleId);

            var query = _roleManager.Roles
                .Where(role => !roleIdsInOrganizationUnit.Contains(role.Id))
                .WhereIf(
                    !input.FilterText.IsNullOrWhiteSpace(),
                    role =>
                        role.DisplayName.Contains(input.FilterText)
                );

            var userCount = await query.CountAsync();
            var users = await query
                .OrderBy(r => r.DisplayName)
                .PageBy(input)
                .ToListAsync();

            return new PagedResultDto<NameValueDto>(
                userCount,
                users.Select(role =>
                    new NameValueDto(
                        $"{role.DisplayName}",
                        role.Id.ToString()
                    )
                ).ToList()
            );
        }
        /// <summary>
        /// 批量从组织中移除角色
        /// </summary>
        /// <param name="roleIds"></param>
        /// <param name="organizationUnitId"></param>
        /// <returns></returns>
        [AbpAuthorize(YoyoSoftPermissionNames.Pages_Administration_OrganizationUnits_ManageRoles)]
        public async Task BatchRemoveRoleFromOrganizationUnit(List<long> roleIds, long organizationUnitId)
        {
            await _organizationUnitRoleRepository.DeleteAsync(ou =>
                roleIds.Contains(ou.RoleId) && ou.OrganizationUnitId == organizationUnitId);
        }
        #endregion
    }
}